﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.SessionState;
using Framework.Library.Base.Extensions;
using Framework.Library.Core.Config;
using Framework.Library.Core.Utils.GlobalHelper;
using Framework.Library.Core.Utils.Text;
using Framework.Library.Data.DAL;
using Framework.Library.Data.DAO;
using ServiceStack.Text;
using Framework.Library.Core.Utils.Database;
using System.Web.Services;
using System.Text;
using System.IO;
using Framework.Library.Data.DAL.JObject;
using Framework.Library.Core.Utils;
using Framework.Library.Core.Utils.Images;
using System.Drawing;
using System.Web.Caching;
using System.Drawing.Imaging;
using Framework.Library.Base.Helper;
using Framework.Library.Core.Provider.Log;

namespace Framework.Portal
{
    /// <summary>
    /// Summary description for Resources
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class Resources : IHttpHandler, IReadOnlySessionState
    {
        public ConfigHelper cfg = new ConfigHelper();


        
        #region IHttpHandler Members

        public void ProcessRequest(HttpContext context)
        {
            string module = context.Request.QueryString["module"];
            if (!string.IsNullOrEmpty(module))
            {
                string jsoncomment = string.Empty;
                switch (module)
                {
                    case "portal":
                        PortalAction(context);
                        break;
                    case "support":
                        SupportAction(context);
                        break;
                    case "popup":
                        PopupAction(context);
                        break;
                    case "contribution":
                        jsoncomment = TeenioAction(context);                        
                        context.Response.ContentType = "application/json";
                        context.Response.Write(jsoncomment);
                        break;
                    case "teenioevent":
                        jsoncomment = TeenioEventAction(context);
                        context.Response.ContentType = "application/json";
                        context.Response.Write(jsoncomment);
                        break;   
                    default:
                        break;
                }
            }
            else
                context.Response.Redirect("Invalid module !");
        }

        public bool IsReusable
        {
            get { return false; }
        }

        #endregion

        private void SupportAction(HttpContext context)
        {
            PortalUser userInfo = context.Session.GetUser();
            if (userInfo != null)
            {
                string action = context.Request.QueryString["action"];
                int portalId = Configurations.PORTALID;
                if (!string.IsNullOrEmpty(action))
                {
                    switch (action)
                    {                                           
                        default:
                            break;
                    }
                }
            }
        }
        private string TeenioEventAction(HttpContext context)
        {
            JResponse responseData = new JResponse();
            try
            {                
                string type = context.Request.Params["action"];
                if (!string.IsNullOrEmpty(type))
                {
                    int eventId;
                    int.TryParse(context.Request.Params["event"], out eventId);
                    switch (type)
                    {                       
                        case "geteventcount":
                            List<TeenioContent> lstContent = ManagerFactory.TeenioContentManager.GetListEvent(eventId);
                            return lstContent.Count.ToString();
                            break;
                        case "geteventinfo":
                            TeenioZone eventInfo = ManagerFactory.DAOEntity.GetInfo<TeenioZone>(new TeenioZone() { ID = eventId });
                            if (eventInfo != null)
                            {
                                responseData.Success = true;
                                responseData.Data = eventInfo;
                            }
                            else
                            {
                                responseData.Success = false;
                                responseData.Message = "Không thể thao tác dữ liệu";
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                responseData.Success = false;
                responseData.Message = ex.Message;
            }
            return JsonSerializer.SerializeToString(responseData);
        }
        private string TeenioAction(HttpContext context)
        {
            string currentUserName = string.Empty;
            int currentUserId = 0;
            if (context.Session.GetUser() != null)
            {
                if (context.Session.GetUser().TYPE == (int)UserType.govn)
                    currentUserId = context.Session.GetUser().DESTUSERID;
                else
                    currentUserId = context.Session.GetUser().USERID;
                currentUserName = context.Session.GetUser().USERNAME;
            }

            JResponse responseData = new JResponse();
            try
            {                
                int articleId;
                int.TryParse(context.Request.Params["articleId"], out articleId);
                if (articleId <= 0)
                {
                    responseData.Success = false;
                    responseData.Message = "Không đúng bài viết";
                    return JsonSerializer.SerializeToString(responseData);
                }
                string type = context.Request.Params["action"];
                if (!string.IsNullOrEmpty(type))
                {
                    switch (type)
                    {
                        case "insertcomment":
                            if (context.Session.GetUser() == null)
                            {
                                responseData.Success = false;
                                responseData.Message = "Chưa đăng nhập !";
                                return JsonSerializer.SerializeToString(responseData);
                            }
                            string message = context.Request.Params["message"];
                            if (string.IsNullOrEmpty(message))
                            {
                                responseData.Success = false;
                                responseData.Message = "Bình luận không được trống";
                            }
                            else
                            {
                                TeenioComment infoComment = new TeenioComment();
                                infoComment.CID = articleId;
                                int userIdComment = currentUserId;
                                infoComment.USERID = userIdComment;
                                infoComment.USERNAME = currentUserName;
                                infoComment.MESSAGE = StringUtils.RemoveHtml(message);
                                infoComment.DATETIME = ConvertUtility.ToUnixTime(DateTime.Now);
                                infoComment.STATUS = (int)CMSWorkFlow.Deploy;
                                infoComment.TYPE = (int)ContributionType.Comment;
                                var resultComment = ManagerFactory.DAOEntity.Insert(infoComment);
                                if (resultComment > 0)
                                {
                                    infoComment.ID = resultComment;
                                    responseData.Success = true;
                                    responseData.Data = infoComment;
                                }
                                else
                                {
                                    responseData.Success = false;
                                    responseData.Message = "Không thể thao tác dữ liệu";
                                }
                            }
                            break;
                        case "insertvote":
                            if (context.Session.GetUser() == null)
                            {
                                responseData.Success = false;
                                responseData.Message = "Chưa đăng nhập !";
                                return JsonSerializer.SerializeToString(responseData);
                            }
                            TeenioComment infoVote = new TeenioComment();
                                
                                infoVote = ManagerFactory.DAOEntity.GetInfo(new TeenioComment() { CID = articleId, USERID = currentUserId });
                                if (infoVote == null)
                                {
                                    infoVote.CID = articleId;
                                    int userIdVote = currentUserId;
                                    infoVote.USERID = userIdVote;
                                    infoVote.USERNAME = currentUserName;
                                    infoVote.MESSAGE = string.Empty;
                                    infoVote.DATETIME = ConvertUtility.ToUnixTime(DateTime.Now);
                                    infoVote.STATUS = (int)CMSWorkFlow.Deploy;
                                    infoVote.TYPE = (int)ContributionType.Like;
                                    var resultVote = ManagerFactory.DAOEntity.Insert(infoVote);
                                    if (resultVote > 0)
                                    {
                                        infoVote.ID = resultVote;
                                        responseData.Success = true;
                                        responseData.Data = infoVote;
                                    }
                                    else
                                    {
                                        responseData.Success = false;
                                        responseData.Message = "Không thể thao tác dữ liệu";
                                    }
                                }
                                else
                                {
                                    responseData.Success = false;
                                    responseData.Message = "Bạn đã bình luận rồi";
                                }
                            break;
                        case "getcontribution":
                            List<TeenioComment> lstCons = ManagerFactory.DAOEntity.GetList(new TeenioComment() { CID = articleId, STATUS = (int)CMSWorkFlow.Deploy });
                            JContribution contribution = new JContribution();
                            if (lstCons != null)
                            {                                
                                List<TeenioComment> lstLikes = lstCons.FindAll(x => x.TYPE == (int)ContributionType.Like);
                                List<TeenioComment> lstComments = lstCons.FindAll(x => x.TYPE == (int)ContributionType.Comment);
                                List<JLike> lstLike = new List<JLike>();
                                List<JComment> lstComment = new List<JComment>();
                                if (lstLikes.Count > 0)
                                {                                    
                                    foreach (TeenioComment like in lstLikes)
                                    {
                                        JLike infoLike = new JLike();
                                        infoLike.CID = like.CID;
                                        infoLike.USERID = like.USERID;
                                        infoLike.USERNAME = like.USERNAME;
                                        lstLike.Add(infoLike);
                                    }
                                }

                                if (lstComments.Count > 0)
                                {
                                    foreach (TeenioComment comment in lstComments)
                                    {
                                        JComment infoComment = new JComment();
                                        infoComment.CID = comment.CID;
                                        infoComment.USERID = comment.USERID;
                                        infoComment.USERNAME = comment.USERNAME;
                                        infoComment.MESSAGE = comment.MESSAGE;
                                        infoComment.DATETIME = comment.DATETIME;
                                        lstComment.Add(infoComment);
                                    }
                                }
                                contribution.Likes = lstLike;
                                contribution.Comments = lstComment;
                            }
                            else
                            {
                                contribution.Likes = new List<JLike>();
                                contribution.Comments = new List<JComment>();
                                responseData.Success = false;
                                responseData.Message = "Không thể thao tác dữ liệu";
                            }
                            return JsonSerializer.SerializeToString(contribution);
                        case "getview":
                            return ManagerFactory.DAOEntity.GetList<TeenioContentHistory>(new TeenioContentHistory() { AUDIOID = articleId }).Count.ToString();
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                responseData.Success = false;
                responseData.Message = ex.Message;
            }
            return JsonSerializer.SerializeToString(responseData);
        }

        private void PortalAction(HttpContext context)
        {
            string action = context.Request.QueryString["action"];
            int userId = Convert.ToInt32(context.Request.Params["u"]);
            if (!string.IsNullOrEmpty(action))
            {
                switch (action)
                {
                    case "changeavatar":
                        string avatar = context.Request.Params["avatar"];
                        ManagerFactory.DAOEntity.Update(new PortalUser() { USERID = userId, AVATAR = avatar });
                        PortalUser info = context.Session.GetUser();
                        if(info != null)
                        {
                            info.AVATAR = avatar;
                            context.Session.Remove(cfg.PrefixMember.VALUE + "MEMBER_INFO");
                            context.Session.Add(cfg.PrefixMember.VALUE + "MEMBER_INFO", info);
                        }
                        break;
                    default:
                        break;
                }
            }
        }
                
        private void PopupAction(HttpContext context)
        {
            string userUploadPath = cfg.UploadDir.VALUE + context.Session.GetUser().USERID + "/" + Configurations.PORTALID + "/";
            if (!Directory.Exists(HttpContext.Current.Server.MapPath(userUploadPath)))
                Directory.CreateDirectory(context.Server.MapPath(userUploadPath));

            string action = context.Request.QueryString["action"];
            StringBuilder sb = new StringBuilder();

            bool isAjax = false;
            if (!string.IsNullOrEmpty(context.Request.Params["ajax"]))                
                bool.TryParse(context.Request.Params["ajax"], out isAjax);
            string pathFile = string.Empty;
            if (!string.IsNullOrEmpty(context.Request.Params["path"]))
                pathFile = context.Request.Params["path"];
            pathFile = HttpUtility.UrlDecode(pathFile);
            if (!Directory.Exists(context.Server.MapPath(pathFile)))
                pathFile = userUploadPath;
            if (!string.IsNullOrEmpty(action))
            {
                switch (action)
                {
                    case "do_action":
                        context.Response.ContentType = "text/plain";
                        string do_action = string.Empty;
                        if (!string.IsNullOrEmpty(context.Request.Params["do"]))
                            do_action = context.Request.Params["do"];
                        switch (do_action)
                        {
                            case "cut_paste":
                                if (!string.IsNullOrEmpty(context.Request.Params["files[]"]))
                                {
                                    if (!string.IsNullOrEmpty(context.Request.Params["folder"]))
                                    {
                                        string[] lstFile = context.Request.Params["files[]"].Split(',');
                                        if (lstFile.Length > 0)
                                            sb.Append(FileHelper.do_cut_paste(lstFile, context.Request.Params["folder"]));
                                        else
                                            sb.Append("error||Không có file hoặc thư mục được chọn");
                                    }
                                    else
                                        sb.Append("error||Không có file hoặc thư mục được chọn");
                                }
                                else
                                    sb.Append("error||Không có file hoặc thư mục được chọn");       
                                break;
                            case "copy_paste":
                                if (!string.IsNullOrEmpty(context.Request.Params["files[]"]))
                                {
                                    if (!string.IsNullOrEmpty(context.Request.Params["folder"]))
                                    {
                                        string[] lstFile = context.Request.Params["files[]"].Split(',');
                                        if (lstFile.Length > 0)
                                            sb.Append(FileHelper.do_copy_paste(lstFile, context.Request.Params["folder"]));
                                        else
                                            sb.Append("error||Không có file hoặc thư mục được chọn");
                                    }
                                    else
                                        sb.Append("error||Không có file hoặc thư mục được chọn");
                                }
                                else
                                    sb.Append("error||Không có file hoặc thư mục được chọn");  
                                break;
                            case "rename":
                                if (!string.IsNullOrEmpty(context.Request.Params["type"]))
                                {
                                    if (!string.IsNullOrEmpty(context.Request.Params["old_filename"]))
                                    {
                                        if (!string.IsNullOrEmpty(context.Request.Params["new_filename"]))
                                        {
                                            string type = context.Request.Params["type"];
                                            string oldname = context.Request.Params["old_filename"];
                                            string newname = context.Request.Params["new_filename"];
                                            newname = newname.Replace(" ", "_");
                                            string folder = userUploadPath;
                                            if (!string.IsNullOrEmpty(context.Request.Params["folder"]))
                                                folder = HttpUtility.UrlDecode(context.Request.Params["folder"]);
                                            oldname = context.Server.MapPath(folder + oldname);
                                            sb.Append(FileHelper.do_rename(type, oldname, newname, folder));
                                        }
                                        else
                                            sb.Append("error||Bạn chưa nhập tên");  
                                    }
                                    else
                                        sb.Append("error||Không có file hoặc thư mục được chọn");  
                                }
                                else
                                    sb.Append("error||Không có file hoặc thư mục được chọn");
                                break;
                            case "delete":
                                if (!string.IsNullOrEmpty(context.Request.Params["files[]"]))
                                {
                                    string[] lstFile = context.Request.Params["files[]"].Split(',');

                                    if (lstFile.Length > 0)
                                        sb.Append(FileHelper.do_delete(lstFile));
                                    else
                                        sb.Append("error||Không có file hoặc thư mục được chọn");
                                }
                                else
                                    sb.Append("error||Không có file hoặc thư mục được chọn");
                                break;
                            case "create_folder":
                                string folderpath = string.Empty;
                                string foldername = string.Empty;
                                if (!string.IsNullOrEmpty(context.Request.Params["folderpath"]) && !string.IsNullOrEmpty(context.Request.Params["foldername"]))
                                {
                                    folderpath = HttpUtility.UrlDecode(context.Request.Params["folderpath"]);
                                    foldername = context.Request.Params["foldername"];
                                    foldername = foldername.Replace(" ", "_");
                                    sb.Append(FileHelper.do_create_folder(foldername, folderpath));
                                }
                                else
                                    sb.Append("error||Không có file hoặc thư mục được chọn");
                                break;
                            default:
                                sb.Append("error||Nothing");
                                break;
                        }
                        context.Response.Write(sb.ToString());
                        break;
                    case "do_upload":
                        context.Response.ContentType = "text/plain";
                        HttpFileCollection htf = context.Request.Files;
                        string uploadpath = string.Empty;
                        if (!string.IsNullOrEmpty(context.Request.Params["uploadpath"]))
                            uploadpath = context.Request.Params["uploadpath"];
                        if (string.IsNullOrEmpty(uploadpath))
                            uploadpath = userUploadPath;
                        uploadpath = HttpUtility.UrlDecode(uploadpath);
                        sb.Append(FileHelper.do_upload(htf, uploadpath));    
                        context.Response.Write(sb.ToString());
                        break;
                    case "view_content":
                        context.Response.ContentType = "text/plain";
                        if (isAjax)
                            sb.Append(FileHelper.view_data(LayoutView.content, pathFile));    
                        context.Response.Write(sb.ToString());
                        break;
                    case "view_details":
                        context.Response.ContentType = "text/plain";
                        if (isAjax)
                            sb.Append(FileHelper.view_data(LayoutView.details, pathFile));    
                        context.Response.Write(sb.ToString());
                        break;
                    case "view_images_large":
                        context.Response.ContentType = "text/plain";
                        if (isAjax)
                            sb.Append(FileHelper.view_data(LayoutView.large_images, pathFile));   
                        context.Response.Write(sb.ToString()); 
                        break;
                    case "view_images_small":
                        context.Response.ContentType = "text/plain";
                        if (isAjax)
                            sb.Append(FileHelper.view_data(LayoutView.small_images, pathFile));  
                        context.Response.Write(sb.ToString());  
                        break;
                    case "view_list":
                        context.Response.ContentType = "text/plain";
                        if (isAjax)
                            sb.Append(FileHelper.view_data(LayoutView.list, pathFile));   
                        context.Response.Write(sb.ToString());                     
                        break;
                    case "view_spec":
                        context.Response.ContentType = "text/plain";
                        if (isAjax)
                        {
                            if (!string.IsNullOrEmpty(context.Request.Params["path"]))
                                pathFile = context.Request.Params["path"];
                            pathFile = HttpUtility.UrlDecode(pathFile);
                            if (!string.IsNullOrEmpty(pathFile))
                            {                                
                                string serverPath = context.Server.MapPath(pathFile);
                                string type = "folder";
                                if (!string.IsNullOrEmpty(context.Request.Params["type"]))
                                    type = context.Request.Params["type"];
                                sb.Append(FileHelper.view_spec(pathFile, type));
                            }
                        }
                        context.Response.Write(sb.ToString());
                        break;
                    case "view_thumb":
                        string fileImage = string.Empty;
                        if (!string.IsNullOrEmpty(context.Request.Params["src"]))
                            fileImage = HttpUtility.UrlDecode(context.Request.Params["src"]);
                        else
                            fileImage = "/Resource/Images/filemanager/256/png.png";
                        int w = 0, h = 0;
                        if (!string.IsNullOrEmpty(context.Request.Params["h"]))
                            int.TryParse(context.Request.Params["h"], out h);
                        if (!string.IsNullOrEmpty(context.Request.Params["w"]))
                            int.TryParse(context.Request.Params["h"], out w);
                        string contentType = string.Empty;
                        byte[] imageContent = FileHelper.view_thumb(fileImage, h, w, out contentType);
                        context.Response.ContentType = contentType;
                        context.Response.BinaryWrite(imageContent);
                        break;
                    case "view_tiles":
                        context.Response.ContentType = "text/plain";
                        if (isAjax)
                            sb.Append(FileHelper.view_data(LayoutView.tiles, pathFile));   
                        context.Response.Write(sb.ToString()); 
                        break;
                    case "view_tree":
                        context.Response.ContentType = "text/plain";
                        if(!string.IsNullOrEmpty(context.Request.Params["p"]))
                            userUploadPath = cfg.UploadDir.VALUE + context.Session.GetUser().USERID + "/" + context.Request.Params["p"] + "/";
                        sb.Append(FileHelper.view_tree(userUploadPath));
                        context.Response.Write(sb.ToString());
                        break;
                    default:
                        break;
                }
            }
        }
    }
}